﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace PSSMS.Tools.Utils
{
    /// <summary>
    /// 把序列化和把序列化为二进制文件的方法封装成泛型方法
    /// </summary>
    public class SerializerBinary
    {
        #region 文件序列化        

        /// <summary>
        /// 2、将对象序列化为文件
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">实例</param>
        /// <param name="path">存放路径</param>
        public static void ObjectToFile<T>(T t, string path)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate))
            {
                formatter.Serialize(stream, t);
                stream.Flush();
            }
        }

        /// <summary>
        /// 4、将文件反序列化为对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="path">路径</param>
        /// <returns>对象</returns>
        public static T FileToObject<T>(string path) where T : class
        {
            using (FileStream stream = new FileStream(path, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                T result = formatter.Deserialize(stream) as T;
                return result;

            }
        }
        #endregion
    }
}
